package com.atg.atgchat.init.config;

import com.atg.atgchat.init.common.factory.MyThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/*
author: atg
time: 2025/1/15 9:07
desc: 自定义-线程池配置
*/
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {
    /**
     * 项目共用线程池
     */
    public static final String ATGCHAT_EXECUTOR = "atgchatExecutor";
    /**
     * websocket通信线程池
     */
    public static final String WS_EXECUTOR = "websocketExecutor";

    /**
     * 线程池最大线程数
     */
    public static final int MAX_POOL_SIZE = 10;
    /**
     * 线程池核心线程数
     */
    public static final int CORE_POOL_SIZE = 5;
    /**
     * 线程池队列大小
     */
    public static final int QUEUE_CAPACITY = 1000;
    public static final String ATGCHAT_EXECUTOR1 = "atgchatExecutor-";

    @Override
    public Executor getAsyncExecutor() {
        return atgchatExecutor();
    }

    @Bean(ATGCHAT_EXECUTOR)
    @Primary
    public ThreadPoolTaskExecutor atgchatExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setThreadNamePrefix(ATGCHAT_EXECUTOR1);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setThreadFactory(new MyThreadFactory(executor));
        executor.initialize();
        return executor;
    }
}
